<?php

class Users_IndexController extends Zend_Controller_Action {

    private $_translate = null;

    public function init() {
        /* Initialize action controller here */
        $this->_translate = Zend_Registry::get('Zend_Translate');
        $this->_helper->layout->setLayout('layout');
    }

    public function indexAction() {
        $userValidation = new Validations_User();
        $valid = $userValidation->hasidentity();
        if ($valid) {
            if ($userValidation->getUserTypeId() != 2) {
                $this->view->message = $this->_translate->_('u_r_not_user');
                Zend_Auth::getInstance()->clearIdentity();
                $this->_redirect('/users/login');
            } else { // Do all work here                
            }
        } else {
            $this->_redirect('/users/login');
        }
    }

    public function loginAction() {
        $this->redirectIfLogedIn();
        $form = new Users_Form_Login();
        $this->view->signInForm = $form;
        $formErrors = array();
        #facebook api
        $api = new Admin_Model_Api();
        $fbActivated = $api->isFacebookActivated();
        $this->view->isFacebookActivated = $fbActivated;
        if ($fbActivated) {
            $facebook = new Facebook_Fb();
            $facebook->setReturnUrl('/users/register');
            $this->view->fbLoginUrl = $facebook->getLoginUrl();
        }
        #redirected from facebook after signup....
        if (isset($_GET['code'])) {
//            $user = $facebook->getUser();
            $userEmail = $facebook->getUserEmail();
//            $token = $facebook->getAccessToken();            
            $email0 = $userEmail[0]['email'];
            $formErrors = $this->doLoginAction($email0, true);
        }
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $formErrors = $this->doLoginAction($values, false);
            }
        }
        if (sizeof($formErrors) > 0) {
            $this->view->formErrors = $formErrors;
        }
    }

    public function registerAction() {
        $this->redirectIfLogedIn();
        $form = new Users_Form_Signup();
        $this->view->signupForm = $form;
        #facebook api
        $api = new Admin_Model_Api();
        $fbActivated = $api->isFacebookActivated();
        $this->view->isFacebookActivated = $fbActivated;
        if ($fbActivated) {
            $facebook = new Facebook_Fb();
            $facebook->setReturnUrl('/users/register');
            $this->view->fbLoginUrl = $facebook->getLoginUrl();
        }
        $formErrors = array();
        #redirected from facebook after signup....
        if (isset($_GET['code'])) {
//            $user = $facebook->getUser();
            $userEmail = $facebook->getUserEmail();
//            $token = $facebook->getAccessToken();
            $emailValidator0 = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
            $email0 = $userEmail[0]['email'];
            if ($emailValidator0->isValid($email0)) {
                array_push($formErrors, $this->_translate->_('email_exists'));
            } else {
                $this->doRegisterAction($email0, true);
            }
        }
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();

                //validating email...
                $emailValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
                $email = $values['email'];
                if ($emailValidator->isValid($email)) {
                    array_push($formErrors, $this->_translate->_('email_exists'));
                } else {
                    //Validating password...
                    if ($values['password1'] != $values['password2']) {
                        array_push($formErrors, $this->_translate->_('pwd_not_matched'));
                    } else {
                        //create new user                       
                        $this->doRegisterAction($values, false);
                    }
                }
                if (sizeof($formErrors) > 0) {
                    $this->view->formErrors = $formErrors;
                }
            }
        }
    }

    public function validationAction() {
        $this->redirectIfLogedIn();
        // set filters and validators for GET input
        $filters = array(
            'key' => array('HtmlEntities', 'StripTags', 'StringTrim')
        );
        $validators = array(
//            'key' => array('Int')
        );
        $input = new Zend_Filter_Input($filters, $validators);
        $input->setData($this->getRequest()->getParams());
        $validation_key = $input->key;
        $data = array(
            'blocked' => false,
            'confirm' => true
        );
        $db = new Users_Model_Users();
        $user = $db->getUserByValidationKey($validation_key);
        if ($user[0]['blocked'] == true) {
            $db->validateUser($data, $user[0]['id']);
            $this->view->message = $this->_translate->_('acc_success_created');
        } else {
            $this->view->message = $this->_translate->_('acc_alerady_verified');
        }
    }

    public function registersuccessAction() {
        $this->redirectIfLogedIn();
        // action body show success page after new registration action.
    }

    public function forgotpasswordAction() {
        $this->redirectIfLogedIn();
        $form = new Users_Form_Forgetpassword();
        $this->view->form = $form;
        $formErrors = array();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $email = $values['email'];

                //checking for email existance in database
                $emailValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
                if ($emailValidator->isValid($email)) {

                    //check email, verified or not...
                    $db = new Users_Model_Users();
                    $user = $db->getValidUserByEmail($email);
                    $p1 = substr($user[0]['validation_key'], 0, 7);
                    $newPass = md5($p1);
                    //set new password in database.
                    $newData = array('password' => $newPass);
                    $db->updateUser($newData, $user[0]['id']);
                    //send email to user.
                    $api = new Sendgrid_Mail();
                    $emailData = array(
                        'toEmail' => $email,
                        'toName' => $email,
                        'subject' => $this->_translate->_('change_password') . ' - ' . $this->_translate->_('project_title'),
                        'body' => $this->_translate->_('ur_new_pass') . ' ' . $p1,
                    );
                    $api->sendMail($emailData);
                    $this->_redirect('/users/forgotsuccess');
                } else {//email not exist in database
                    array_push($formErrors, $this->_translate->_('email_not_exists'));
                }
                if (sizeof($formErrors) > 0) {
                    $this->view->formErrors = $formErrors;
                }
            }
        }
    }

    public function forgotsuccessAction() {
        $this->redirectIfLogedIn();
        // action body
    }

    public function getAuthAction() {
        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
        $authAdapter->setTableName('users')
                ->setIdentityColumn('email')
                ->setCredentialColumn('password');
        return $authAdapter;
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/users/login');
    }

    public function redirectIfLogedIn() {
        $userValidation = new Validations_User();
        $valid = $userValidation->hasidentity();
        if ($valid) {
            if ($userValidation->getUserTypeId() != 2) {
                $this->view->message = $this->_translate->_('u_r_not_user');
                Zend_Auth::getInstance()->clearIdentity();
            } else {
                $this->_redirect('/users/profile');
            }
        }
    }

    public function resendactivationemailAction() {
        $form = new Users_Form_ResendActivationEmail();
        $this->view->form = $form;
        $formErrors = array();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $email = $values['email'];
                $db = new Users_Model_Users();
                $user = $db->getValidUserByEmail($email);
                $emailValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
                if ($emailValidator->isValid($email)) {
                    if (!$user[0]['confirm']) {
                        $validation_key = $user[0]['validation_key'];
                        $varificationLink = 'http://' . $_SERVER['SERVER_NAME'] . '/users/validation/' . $validation_key;
                        $message = "<a href=$varificationLink>" . $this->_translate->_('click_link_for_verify') . "</a>";
                        //send email to user
                        $api = new Sendgrid_Mail();
                        $emailData = array(
                            'toEmail' => $email,
                            'toName' => $email,
                            'subject' => $this->_translate->_('welcome_to') . ' ' . $this->_translate->_('project_title'),
                            'body' => $message
                        );
                        $api->sendMail($emailData);
                        $this->_redirect('/users/register/next');
                    } else {
                        array_push($formErrors, $this->_translate->_('acc_already_verified'));
                    }
                } else {
                    array_push($formErrors, $this->_translate->_('email_not_exists'));
                }
                if (sizeof($formErrors) > 0) {
                    $this->view->formErrors = $formErrors;
                }
            }
        }
    }

    public function doRegisterAction($values, $isFacebook) {
        $password = '';
        $email = '';
        if ($isFacebook) {
            $password = md5('facebook');
            $email = $values;
        } else {
            $password = md5($values['password1']);
            $email = $values['email'];
        }
        $validation_key = strtoupper(md5($email));
        $db = new Users_Model_Users();
        $dbData = array(
            'email' => $email,
            'blocked' => true,
            'password' => $password,
            'validation_key' => $validation_key,
            'membership_type' => 1,
            'user_type' => 2,
            'confirm' => false,
            'reg_date' => date('Y-m-d', date('U'))
        );
        $db->createUser($dbData); //query to database
        $varificationLink = 'http://' . $_SERVER['SERVER_NAME'] . '/users/validation/' . $validation_key;
        $message = "<a href=$varificationLink>" . $this->_translate->_('click_link_for_verify') . "</a>";
        //send email to user
        $api = new Sendgrid_Mail();
        $emailData = array(
            'toEmail' => $email,
            'toName' => $email,
            'subject' => $this->_translate->_('welcome_to') . ' ' . $this->_translate->_('project_title'),
            'body' => $message
        );
        $api->sendMail($emailData);
        $this->_redirect('/users/register/next');
    }

    public function doLoginAction($values, $isFacebook) {
        $formErrors = array();
        $loginEmail = '';
        $loginPassword = '';
        if ($isFacebook) {
            $loginEmail = $values;
            $loginPassword = md5('facebook');
        } else {
            $loginEmail = $values['email'];
            $loginPassword = md5($values['password']);
        }

        //checking for email existance in database
        $emailValidator = new Zend_Validate_Db_RecordExists(array('table' => 'users', 'field' => 'email'));
        if ($emailValidator->isValid($loginEmail)) {

            //check email, verified or not...
            $db = new Users_Model_Users();
            $user = $db->getValidUserByEmail($loginEmail);
            if ($user[0]['blocked'] == true) {
                array_push($formErrors, $this->_translate->_('user_blocked_by_admin'));
            } else if (!$user[0]['confirm']) {
                array_push($formErrors, $this->_translate->_('email_not_verified'));
            } else {
                if ($user[0]['password'] != $loginPassword) {
                    array_push($formErrors, $this->_translate->_('invalid_pass'));
                } else {//email and password are valid
                    $authAdapter = $this->getAuthAction();
                    $authAdapter->setIdentity($loginEmail)
                            ->setCredential($loginPassword);
                    $auth = Zend_Auth::getInstance();
                    $result = $auth->authenticate($authAdapter);
                    if ($result->isValid()) {
                        $identity = $authAdapter->getResultRowObject();
                        $authStorage = $auth->getStorage();
                        $authStorage->write($identity);
                        $this->_redirect('/home');
                    }
                }
            }
        } else {//email not exist in database
            array_push($formErrors, $this->_translate->_('email_not_exists'));
        }
        return $formErrors;
    }

}

